package com.hnu.store.utils;

import com.alibaba.fastjson.JSON;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

public class Certificate {

  public static Map certify(String front,String negative) {
    String host = "https://idocrhj.market.alicloudapi.com";
    String path = "/ocr/idcard";
    String method = "POST";
    String appcode = "cd43c8d00d87478dbeb6c5217159e3ea";
    Map<String, String> headers = new HashMap<String, String>();
    //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
    headers.put("Authorization", "APPCODE " + appcode);
    //根据API的要求，定义相对应的Content-Type
    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    Map<String, String> querys = new HashMap<String, String>();
    Map<String, String> bodys = new HashMap<String, String>();
    //  正面base64字符串
    bodys.put("front", front);
    //  背面base64字符串
    bodys.put("negative", negative);

    HttpResponse response;
    try {
      response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    System.out.println(response.toString());
    //  获取response的body
    Map result;
    try {
      String tempString = EntityUtils.toString(response.getEntity());
      System.out.println(tempString);
      result = JSON.parseObject(tempString,Map.class);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    return result;
  }

  /**
   * 文件File类型转BASE64
   *
   * @param file
   * @return
   */
  public static String fileToBase64(File file) {
    return "data:image/png;base64," + Base64.encodeBase64String(fileToByte(file));
  }

  /**
   * 文件File类型转byte[]
   *
   * @param file
   * @return
   */
  private static byte[] fileToByte(File file) {
    byte[] fileBytes = null;
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(file);
      fileBytes = new byte[(int) file.length()];
      fis.read(fileBytes);
      fis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return fileBytes;
  }



}
